#include "protocol_parser.h"
#include <cstring>

namespace network {

ProtocolParser::ProtocolParser()
    : state_(ParseState::HEADER)
    , bytes_parsed_(0)
{
    current_message_ = std::make_shared<Message>();
}

ProtocolParser::ParseState ProtocolParser::parse(const char* data, size_t length)
{
    size_t bytes_remaining = length;
    
    while (bytes_remaining > 0) {
        if (state_ == ParseState::HEADER) {
            size_t header_bytes_needed = Message::header_length - bytes_parsed_;
            size_t bytes_to_copy = std::min(header_bytes_needed, bytes_remaining);
            
            std::memcpy(current_message_->data() + bytes_parsed_, data, bytes_to_copy);
            bytes_parsed_ += bytes_to_copy;
            data += bytes_to_copy;
            bytes_remaining -= bytes_to_copy;
            
            if (bytes_parsed_ == Message::header_length) {
                if (current_message_->decode_header()) {
                    state_ = ParseState::BODY;
                    bytes_parsed_ = 0;
                } else {
                    // 无效的消息头，重置解析器
                    reset();
                    return ParseState::HEADER;
                }
            }
        } else if (state_ == ParseState::BODY) {
            size_t body_bytes_needed = current_message_->body_length() - bytes_parsed_;
            size_t bytes_to_copy = std::min(body_bytes_needed, bytes_remaining);
            
            std::memcpy(current_message_->body() + bytes_parsed_, data, bytes_to_copy);
            bytes_parsed_ += bytes_to_copy;
            data += bytes_to_copy;
            bytes_remaining -= bytes_to_copy;
            
            if (bytes_parsed_ == current_message_->body_length()) {
                state_ = ParseState::COMPLETE;
                return state_;
            }
        }
    }
    
    return state_;
}

std::shared_ptr<Message> ProtocolParser::get_message() const
{
    return current_message_;
}

void ProtocolParser::reset()
{
    current_message_ = std::make_shared<Message>();
    state_ = ParseState::HEADER;
    bytes_parsed_ = 0;
}

} // namespace network    